//
//  BIDOwnPublishViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/19.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDOwnPublishViewController.h"
#import "BIDBaseListView.h"
#import "BIDGoodsForExchangeCell.h"
#import "BIDRentCell.h"
#import "BIDSaleHouseCell.h"
#import "BIDMyPublishMenuView.h"
#import "BIDPublishExchangeInfoViewController.h"
#import "BIDPublishRentInfoViewController.h"
#import "BIDPublishSaleHouseInfoViewController.h"

#import "UITableView+BIDHaveEmptyData.h"

#import <SDWebImage/UIImageView+WebCache.h>

@interface BIDOwnPublishViewController ()<BIDBaseListViewDelegate, BIDMyPublishMenuViewDelegate, BIDGoodsForExchangeCellDelegate, BIDRentCellDelegate, BIDSaleHouseCellDelegate>
{
    NSMutableArray *_dataSourceArr;
    NSMutableArray *_menuArr;
    NSMutableArray *_labelArr;
    UILabel *_lineLabel;
    NSUInteger _curPage;
    NSUInteger _countPerPage;
    //当前选中的菜单的索引
    NSUInteger _selectMenuIndex;
    BOOL _isRegister;
    BIDMyPublishMenuView *_menuView;
    UIView *_maskView;
    NSIndexPath *_selectIndexPath;
}
@end

@implementation BIDOwnPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的发布";
    // Do any additional setup after loading the view from its nib.
    _curPage = 0;
    _countPerPage = 15;
    _tableView.myDelegate = self;
    _dataSourceArr = [NSMutableArray array];
    _labelArr = [NSMutableArray array];
    NSString *strUserID = [AppDelegate getUserId];
    NSArray *arr = @[@{@"title":@"爱置换", @"requestURL":@"displaceAndroid/list.action", @"params":@{@"searchParam.memberId":strUserID}, @"className":@"", @"curPage":@0, @"data":[NSArray array], @"height":@80},
                  @{@"title":@"房屋出租", @"requestURL":@"rentAndroid/list.action", @"params":@{@"searchParam.memberId":strUserID}, @"className":@"", @"curPage":@0, @"data":[NSArray array], @"height":@109},
                 @{@"title":@"房屋出售", @"requestURL":@"saleAndroid/list.action", @"params":@{@"searchParam.memberId":strUserID}, @"className":@"", @"curPage":@0, @"data":[NSArray array], @"height":@109}];
    _menuArr = [[NSMutableArray alloc] initWithArray:arr];
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _menuView = [[[NSBundle mainBundle] loadNibNamed:@"BIDMyPublishMenuView" owner:self options:nil] lastObject];
    CGRect menuViewFrame = _menuView.frame;
    menuViewFrame.size.width = screenSize.width;
    _menuView.frame = menuViewFrame;
    _menuView.delegate = self;
    //
    _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height-64)];
    [_maskView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.4f)];
    UITapGestureRecognizer *tapGR1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler1:)];
    [_maskView addGestureRecognizer:tapGR1];
    //
    _tableView.allowsSelection = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self prepareForLayout];    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _curPage = 0;
    [_dataSourceArr removeAllObjects];
    [self loadData];
}

- (void)loadData
{
    _curPage++;
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], _menuArr[_selectMenuIndex][@"requestURL"]];
    NSDictionary *tempDic = _menuArr[_selectMenuIndex][@"params"];
    NSMutableString *tempStr = [NSMutableString string];
    NSEnumerator *enumerator = [tempDic keyEnumerator];
    id key;
    while(key = [enumerator nextObject])
    {
        [tempStr appendFormat:@"%@=%@", key, tempDic[key]];
    }
    NSString *strPost = [[NSString alloc] initWithFormat:@"page=%ld&rows=%ld&%@", _curPage, _countPerPage, tempStr];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [_dataSourceArr addObjectsFromArray:responseDic[@"rows"]];
            if(_dataSourceArr.count < _curPage*_countPerPage)
            {
                [_tableView hasNoMoreData];
            }
            else
            {
                [_tableView hasMoreData];
            }
        }
        [_tableView reloadData];
        if(_dataSourceArr.count == 0)
        {
            [_tableView showEmptyView];
        }
        else
        {
            [_tableView hideEmptyView];
        }
    }];
}

- (void)prepareForLayout
{
    //创建顶部菜单
    [self createMenu];
}

- (void)createMenu
{
    NSUInteger leftSpacing = 0.f;
    NSUInteger itemSpacing = 0.f;
    UIColor *highlightColor = RGBACOLOR(27, 211, 205, 1.f);
    //
    int count = 0;
    for(NSDictionary *dic in _menuArr)
    {
        NSString *strContent = dic[@"title"];
        UILabel *label = [self createLabelWithContent:strContent];
        label.tag = count;
        CGRect labelFrame = label.frame;
        CGFloat posY = (CGRectGetHeight(_scrollView.frame)-CGRectGetHeight(label.frame))/2;
        if(count == 0)
        {
            _lineLabel = [self createLineLabel];
            CGRect lineLabelFrame = _lineLabel.frame;
            labelFrame.origin.x = leftSpacing;
            labelFrame.origin.y = posY;
            [label setTextColor:highlightColor];
            lineLabelFrame.origin.x = labelFrame.origin.x;
            lineLabelFrame.origin.y = CGRectGetMaxY(labelFrame)+5;
            lineLabelFrame.size.width = labelFrame.size.width;
            _lineLabel.frame = lineLabelFrame;
            [_scrollView addSubview:_lineLabel];
        }
        else
        {
            UILabel *frontLabel = _labelArr[count-1];
            labelFrame.origin.x = CGRectGetMaxX(frontLabel.frame) + itemSpacing;
            labelFrame.origin.y = posY;
        }
        label.frame = labelFrame;
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:tapGR];
        [_labelArr addObject:label];
        [_scrollView addSubview:label];
        count++;
    }
    CGSize contentSize = _scrollView.contentSize;
    UILabel *tempLabel = _labelArr[_labelArr.count-1];
    contentSize.width = CGRectGetMaxX(tempLabel.frame)+itemSpacing;
    [_scrollView setContentSize:contentSize];
}

- (UILabel *)createLabelWithContent:(NSString *)content
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    NSUInteger labelHeight = 21.f;
    UIFont *labelFont = [UIFont systemFontOfSize:15.f];
    UIColor *normalColor = RGBACOLOR(57, 54, 59, 1.f);
    //CGFloat width = [BIDGlobalMethods getWidthWithString:content font:labelFont constraintSize:CGSizeMake(MAXFLOAT, labelHeight)];
    CGFloat width = screenSize.width / _menuArr.count;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, labelHeight)];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setTextColor:normalColor];
    [label setFont:labelFont];
    [label setText:content];
    return label;
}

- (UILabel *)createLineLabel
{
    NSUInteger labelHeight = 1.f;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 5, labelHeight)];
    [label setBackgroundColor:RGBACOLOR(27, 211, 205, 1.f)];
    return label;
}

/**
 切换数据源

 @param tapGR <#tapGR description#>
 */
- (void)tapGestureHandler:(UITapGestureRecognizer *)tapGR
{
    UILabel *tempLabel = (UILabel *)tapGR.view;
    if(_selectMenuIndex == tempLabel.tag) return;
    UIColor *highlightColor = RGBACOLOR(27, 211, 205, 1.f);
    UIColor *normalColor = RGBACOLOR(57, 54, 59, 1.f);
    for(UILabel *label in _labelArr)
    {
        [label setTextColor:normalColor];
    }
    [tempLabel setTextColor:highlightColor];
    CGRect lineFrame = _lineLabel.frame;
    lineFrame.origin.x = CGRectGetMinX(tempLabel.frame);
    lineFrame.size.width = CGRectGetWidth(tempLabel.frame);
    _lineLabel.frame = lineFrame;
    //保存现有的
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_menuArr[_selectMenuIndex]];
    [dic setObject:_dataSourceArr forKey:@"data"];
    [dic setObject:[NSNumber numberWithInteger:_curPage] forKey:@"curPage"];
    [_menuArr replaceObjectAtIndex:_selectMenuIndex withObject:dic];
    //替换为当前选中的
    _selectMenuIndex = tempLabel.tag;
    NSDictionary *tempDic = _menuArr[_selectMenuIndex];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:tempDic[@"data"]];
    NSNumber *pageValue =tempDic[@"curPage"];
    _curPage = [pageValue integerValue];
    //
    if(_dataSourceArr.count == 0)
    {
        [self loadData];
    }
    else
    {
        [_tableView hideEmptyView];
        [_tableView reloadData];
    }
}

/**
 隐藏编辑菜单

 @param tapGR <#tapGR description#>
 */
- (void)tapGestureHandler1:(UITapGestureRecognizer *)tapGR
{
    [self hideMenuView];
}

- (void)showMenuViewAtIndexPath:(NSIndexPath *)indexPath sender:(UIButton *)btn
{
    CGRect rect1 = [btn convertRect:btn.frame fromView:btn.superview];
    CGRect rect2 = [btn convertRect:rect1 toView:self.view];
    CGRect frame = _menuView.frame;
    frame.origin.y = CGRectGetMaxY(rect2)+5;
    _menuView.frame = frame;
    [self.view addSubview:_maskView];
    [self.view addSubview:_menuView];
}

- (void)hideMenuView
{
    [_maskView removeFromSuperview];
    [_menuView removeFromSuperview];
}

- (void)alertViewHandler
{
    //[_tableView reloadData];
}

#pragma mark - BIDGoodsForExchangeCellDelegate
#pragma mark - BIDRentCellDelegate
- (void)showEditableViewAtIndexPath:(NSIndexPath *)indexPath sender:(UIButton *)btn
{
    _selectIndexPath = indexPath;
    [self showMenuViewAtIndexPath:indexPath sender:btn];
}

#pragma mark - BIDMyPublishMenuViewDelegate

/**
 删除
 */
- (void)toDelete
{
    [self hideMenuView];
    NSString *strRequestURL = @"";
    NSString *strPost = @"";
    NSDictionary *dic = _dataSourceArr[_selectIndexPath.row];
    switch(_selectMenuIndex)
    {
        case 0:
        {
            //爱置换
            strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], @"displaceAndroid/remove.action"];
            strPost = [[NSString alloc] initWithFormat:@"memberId=%@&ids=%@", [AppDelegate getUserId], dic[@"id"]];
        }
            break;
        case 1:
        {
            //出租
            strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], @"rentAndroid/remove.action"];
            strPost = [[NSString alloc] initWithFormat:@"ids=%@", dic[@"id"]];
        }
            break;
        case 2:
        {
            //出售
            strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], @"saleAndroid/remove.action"];
            strPost = [[NSString alloc] initWithFormat:@"ids=%@", dic[@"id"]];
        }
            break;
    }
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [_dataSourceArr removeObjectAtIndex:_selectIndexPath.row];
            [_tableView deleteRowsAtIndexPaths:@[_selectIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            //[self showAlertView:@"操作成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
        }
    }];
}

/**
  编辑
 */
- (void)toEdit
{
    [self hideMenuView];
    switch(_selectMenuIndex)
    {
        case 0:
        {
            //爱置换
            BIDPublishExchangeInfoViewController *vc = [[BIDPublishExchangeInfoViewController alloc] initWithNibName:@"BIDPublishExchangeInfoViewController" bundle:nil];
            vc.goodsDic = [[NSDictionary alloc] initWithDictionary:_dataSourceArr[_selectIndexPath.row]];
            vc.isEdit = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            //出租
            BIDPublishRentInfoViewController *vc = [[BIDPublishRentInfoViewController alloc] initWithNibName:@"BIDPublishRentInfoViewController" bundle:nil];
            vc.rentInfoDic = [[NSDictionary alloc] initWithDictionary:_dataSourceArr[_selectIndexPath.row]];
            vc.isEdit = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {
            //出售
            BIDPublishSaleHouseInfoViewController *vc = [[BIDPublishSaleHouseInfoViewController alloc] initWithNibName:@"BIDPublishSaleHouseInfoViewController" bundle:nil];
            vc.saleHouseDic = [[NSDictionary alloc] initWithDictionary:_dataSourceArr[_selectIndexPath.row]];
            vc.isEdit = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
    }
}

#pragma mark - UITableViewDelegate
/**
 *  结束下拉刷新和上拉加载更多的旋转动画
 */
- (void)externalTask
{
    [_tableView endRefresh];
    [_tableView hasNoMoreData];
}

#pragma mark - BIDBaseListViewDelegate
/**
 *  下拉刷新
 */
- (void)refresh
{
    NSLog(@"refresh");
    _curPage = 0;
    NSArray *arr = _dataSourceArr;
    if(arr.count>0)
    {
        if([arr[0] isKindOfClass:[NSArray class]] && arr.count>1)
        {
            //多个section
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, arr.count)];
            [_tableView beginUpdates];
            [_tableView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            [_dataSourceArr removeAllObjects];
            [_tableView endUpdates];
        }
        else
        {
            //只有一个section
            NSMutableArray *indexPathArr = [NSMutableArray array];
            for(int i=0; i<arr.count; i++)
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPathArr addObject:indexPath];
            }
            [_tableView beginUpdates];
            [_dataSourceArr removeAllObjects];
            [_tableView deleteRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationAutomatic];
            [_tableView endUpdates];
        }
    }
    [self loadData];
}
/**
 *  上拉加载更多
 */
- (void)loadMoreData
{
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier1 = @"identifier1";
    static NSString *identifier2 = @"identifier2";
    static NSString *identifier3 = @"identifier3";
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        //置换
        UINib *nib1 = [UINib nibWithNibName:@"BIDGoodsForExchangeCell" bundle:nil];
        [tableView registerNib:nib1 forCellReuseIdentifier:identifier1];
        //租房
        UINib *nib2 = [UINib nibWithNibName:@"BIDRentCell" bundle:nil];
        [tableView registerNib:nib2 forCellReuseIdentifier:identifier2];
        //售房
        UINib *nib3 = [UINib nibWithNibName:@"BIDSaleHouseCell" bundle:nil];
        [tableView registerNib:nib3 forCellReuseIdentifier:identifier3];
    }
    NSDictionary *dic = _dataSourceArr[row];
    switch(_selectMenuIndex)
    {
        case 0:
        {
            //爱置换
            BIDGoodsForExchangeCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:identifier1];
            [goodsCell showMenuBtn];
            goodsCell.delegate = self;
            goodsCell.indexPath = indexPath;
            goodsCell.titleLabel.text = dic[@"title"];
            goodsCell.priceLabel.text = [[NSString alloc] initWithFormat:@"￥%@", ANY2NSSTRING(dic[@"price"])];
            NSString *strTime = dic[@"createTime"];
            NSDate *date = [BIDGlobalMethods transToNSDateByFormatter:@"yyyy-MM-dd HH-mm-ss" fromStringDate:strTime];
            goodsCell.timeLabel.text = [date timeIntervalDescription];
            //
            NSDictionary *picDic = nil;
            NSArray *fileArr = dic[@"fileList"];
            if(fileArr.count > 0)
            {
                picDic = fileArr[0];
                NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], picDic[@"path"]];
                [goodsCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"pic_placeholder.png"]];
            }
            else
            {
                [goodsCell.imgView setImage:[UIImage imageNamed:@"pic_placeholder.png"]];
            }
            cell = goodsCell;
        }
            break;
        case 1:
        {
            //出租
            BIDRentCell *rentCell = [tableView dequeueReusableCellWithIdentifier:identifier2];
            [rentCell showMenuBtn];
            rentCell.delegate = self;
            rentCell.indexPath = indexPath;
            NSDictionary *dic = _dataSourceArr[row];
            NSArray *fileArr = dic[@"fileList"];
            if(fileArr && fileArr.count>0)
            {
                NSDictionary *fileDic = fileArr[0];
                NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], fileDic[@"path"]];
                [rentCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"pic_placeholder.png"]];
            }
            else
            {
                [rentCell.imgView setImage:[UIImage imageNamed:PIC_PLACEHOLDER]];
            }
            rentCell.titleLabel.text = [[NSString alloc] initWithFormat:@"%@\r ", dic[@"content"]];
            rentCell.rentTypeLabel.text = [[NSString alloc] initWithFormat:@"%@ %@", dic[@"houseTypeName"], dic[@"rentModeName"]];
            NSString *strPrice = ANY2NSSTRING(dic[@"rental"]);
            NSNumber *payModeValue = dic[@"payMode"];
            NSString *strExtention = @"";
            switch([payModeValue integerValue])
            {
                case 1:
                {
                    strExtention = @"月";
                }
                    break;
                case 2:
                {
                    strExtention = @"季度";
                }
                    break;
                case 3:
                {
                    strExtention = @"年";
                }
                    break;
            }
            rentCell.priceLabel.text = [[NSString alloc] initWithFormat:@"%@元/%@", strPrice, strExtention];
            cell = rentCell;
        }
            break;
        case 2:
        {
            //出售
            BIDSaleHouseCell *saleHouseCell = [tableView dequeueReusableCellWithIdentifier:identifier3];
            [saleHouseCell showMenuBtn];
            saleHouseCell.delegate = self;
            saleHouseCell.indexPath = indexPath;
            NSDictionary *dic = _dataSourceArr[row];
            NSArray *fileArr = dic[@"fileList"];
            if(fileArr && fileArr.count>0)
            {
                NSDictionary *fileDic = fileArr[0];
                NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], fileDic[@"path"]];
                [saleHouseCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"pic_placeholder.png"]];
            }
            else
            {
                [saleHouseCell.imgView setImage:[UIImage imageNamed:PIC_PLACEHOLDER]];
            }
            saleHouseCell.titleLabel.text = [[NSString alloc] initWithFormat:@"%@\r ", dic[@"content"]];
            saleHouseCell.rentTypeLabel.text = [[NSString alloc] initWithFormat:@"%@ %@㎡", dic[@"houseTypeName"], dic[@"area"]];
            NSString *strPrice = ANY2NSSTRING(dic[@"price"]);
            saleHouseCell.priceLabel.text = [[NSString alloc] initWithFormat:@"%@万", strPrice];
            cell = saleHouseCell;
        }
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _menuArr[_selectMenuIndex];
    NSNumber *value = dic[@"height"];
    return [value floatValue];
}

@end
